// 与ows交互
const { get, merge } = require('lodash');
const got = require('got');
const parseStringPromise = require('xml2js').parseStringPromise;
const { getConfig } = require('../utils');
const { logger } = require('./logger');

exports.request = async function (options) {
	const config = getConfig();
	const server = get(config, 'ows.server');

	const init = {
		url: server,
		method: 'POST',
		body: options.xml,
		headers: {
			'Content-Type': 'text/xml; charset=utf-8',
			'Accept-Encoding': 'gzip, deflate',
			Connect: 'keep-alive',
		}
	};

	let _options = merge(init, options);
	_options.url += options.cupath;
	delete _options.cupath;
	delete _options.xml;

	logger.debug('——>', JSON.parse(JSON.stringify(_options).replace(/\\t/ig, '').replace(/\\n/ig, '')));
	const res = await got(_options);

	const { statusCode, statusMessage, body } = res;

	if (statusCode === 200) {
		logger.debug('<——', body);

		const jsonData = await parseStringPromise(body);

		return {
			xmlData: body,
			jsonData
		};
	}

	throw new Error(`OWS request failed, statusCode: ${statusCode}, statusMessage: ${statusMessage}`);
};
